<?php if( ! defined('BASEPATH')) exit('No direct script access allowed');
/********************
 *@param function:Order WebApp home
 *@param datetime 2015-05-05
 *@param author abin
 ********************/
class Home extends Lang_Controller {

  public function __construct(){
    parent::__construct();
   
    
    $this->data['active']='home';
    $this->load->model('categorys_mdl');
    $this->load->model('products_mdl');
    $this->load->model('orders_mdl');
    $this->load->model('specs_mdl');
    $this->load->model('admins_mdl');
    //echo $this->products_mdl->getSpecItemName('555_570_590_781_1039');exit;
    $palyerid = $this->admins_mdl->get_member_palyers();
    $lan_get =  $this->input->get('lan','');
      $lan_get = empty($lan_get) ? get_cookie('language') : $lan_get;
      if(empty($lan_get) || !in_array($lan_get,array('zh-tw','english'))){
          $lan_get = 'zh-tw';
      }
      $this->lang->load('page', $lan_get);
      set_cookie('language',$lan_get,time()+24*3600*30);
      if($lan_get=='zh-tw'){
          $this->settings_mdl->edit_settings_by_key(array('value'=>1),'default_language');
      }elseif($lan_get=='english'){
          $this->settings_mdl->edit_settings_by_key(array('value'=>2),'default_language');
      }
      $this->data['getlang'] = $lan_get;
      $this->data['lang'] =$this->lang->language;
      $this->cart_attrs = $this->nsession->userdata('cart_attrs');
      // $unitPrice = $this->specs_mdl->getProductItemUnitPrice('1846_1853_116');
  }

  public function index(){
    //$this->_get_logo('home','logo');
    $this->_get_adv('home','banner1');
    $this->_get_menu('home','menu');
    $this->get_categorys();
    $this->get_products();
    $this->_page_info();//基本頁面列表
    $this->data['payments'] = $this->orders_mdl->get_payments(array('status'=>1));

    $carts = $this->nsession->userdata('carts');
    $this->data['carts'] = empty($carts) ? array() : $carts;
    $this->load->view('home_list_view',$this->data);
    //$this->nsession->set_session('carts',null);
  }
  public function detail(){
    $product_id = $this->input->get('product_id');
  $lang_id = $this->data['default_language'];
    $product = $this->products_mdl->get_products_by_id($product_id);
    $query = $this->products_mdl->get_descriptions($product_id,$lang_id);
    if($query){
      $this->data['row'] = $query->row_array();
      $this->data['row']['content'] = format_content_tags($this->data['row']['content']);
    }
    $this->data['base'] = $product;
    $img[] = $product['main_image'];
    if(!empty($product['photo'])){
      $photo = unserialize($product['photo']);
      if(is_array($photo) && count($photo) > 0){
          $img = array_merge($img,$photo);
      }
    }
    $this->data['photo'] = $img;
    $this->_get_logo('home','logo');
    $carts = $this->nsession->userdata('carts');
    $this->data['carts'] = empty($carts) ? array() : $carts;
    $this->data['lang'] =$this->lang->language;
    $this->load->view('detail_view',$this->data);
  }
  //獲取分類
  private function get_categorys(){
    $data=array('language_id'=>$this->data['lang_id'],'parent_id'=>0,'status'=>1);
    $this->data['categorys']=$this->categorys_mdl->getCategories($data);
  }

  //獲取對應的產品
  public function get_products(){

    $category_id=$this->input->post('category_id',true);
    $is_ajax=$this->input->post('is_ajax',true);

    $product_string=$this->input->post('product_string',true);//購物車的東西
    $cart_array= $this->nsession->userdata('carts'); //$this->_get_product_array($product_string);

    $page = $this->input->post('page',TRUE);
    $page = (!empty($page) && is_numeric($page)) ? intval($page) : 1;

    $limit = 8;
    $offset = ($page - 1) * $limit;
    $keyword=$this->input->post('keywords',true);
    $data=array(
      'language_id'=>$this->data['lang_id'],
      'status'=>1,
      'field'=>'n.sort_order ASC,n.add_time',
      'sort'=>'desc',
      'title' => $keyword,
      'number' => $keyword,
      'limits'=>$limit,
      'offset'=>$offset,
      'category_id'=>$category_id,
    );

    $lists=$this->products_mdl->get_products($data);

    $this->data['lists']=$lists;
    
    if($is_ajax){
      header('Content-Type: application/json; charset=utf-8');
      $html='';
      if(!empty($lists) && $lists->num_rows()>0){
        foreach ($lists->result_array() as $list){
          $thumb_img=!empty($list['main_image']) && file_exists($list['main_image'])?base_url(Imagelib::resize_thumb($list['main_image'],100,100,FALSE)):base_url('themes/front/img/no-image.png');
          $large_image=!empty($list['main_image']) && file_exists($list['main_image'])?base_url(Imagelib::resize_thumb($list['main_image'],450,450,FALSE)):base_url('themes/front/img/no-image-large.png');
          $price='$'.$list['price'];
          //判斷是否存在購物車內.
          $select_style='';
          $select_num='1';
          if(!empty($cart_array) && is_array($cart_array)){
            $select_style=array_key_exists($list['id'],$cart_array)?'style="display:block"':$select_style;
            $select_num=array_key_exists($list['id'],$cart_array)?$cart_array[$list['id']]:$select_num;
          }
         // $number=!empty($list['number'])?'<p class="number">'.$list['number'].'</p>':null;
          $introduction=!empty($list['introduction'])?'<p class="details">'.$list['introduction'].'</p>':null;
          $unit=!empty($list['unit'])?'/'.$list['unit']:'';
          $_price=check_product_itemprice($list['id']) ? '1' : '0';
          $old_price = !empty($list['old_price']) ? "<s class=''>HK$".$list['old_price']."</s>": '';
          $price = !empty($list['old_price']) ? '<span class="price">HK$'.$list['price'].'</span>': '';
          //$number = !empty($list['number']) ? "<span class=''>NO.".$list['number']."</span>": '';
          $number = !empty($list['number']) ? "<span class=''>NO.".$list['number']." - <b style='color:#FF7F00;'>".$list['title']."</b></span>": '';
          $detai_url = base_url("home/detail")."?product_id=".$list['id'];
          $hos = null;
          if($list['is_spec'] == 2){
            $hos = '<span class="hot"><img class="icon-hot" src="'.base_url('/themes/front/img/icon-hot.png').'"></span>';
          }
          if($list['is_spec'] == 1){
            $hos = '<span class="hot"><img class="icon-hot" src="'.base_url('/themes/front/img/icon-new.png').'"></span>';
          }
          $text = $this->data['lang']['home_lable_3'];
          $btn = $this->data['lang']['home_lable_6'];
          $html.=<<<EOT
          <li class="product product_{$list['id']}" product_id="{$list['id']}" data-aid="{$list['id']}" data-price="{$_price}">
            <div class="cover">
              <figure class="cover_son" itemprop="associatedMedia" itemscope>
              <a href="{$large_image}" itemprop="contentUrl" data-size="800x450">
                <img src="{$thumb_img}" itemprop="thumbnail" alt="Image description" width="100" height="57" /><i></i>
              </a>
              </figure>
            </div>
            <p class="price-block">
               {$old_price}
                {$price}
              {$number}
          </p>
            <p class="title">{$list['title']}</p>
            {$introduction}
            <p class=" btn-block">
               <span class="btn add-cart-btn" type="button"><span>{$text}</span></span>
              <span class="select">
                  <a class="minus" data-role="none" href="javascript:void(0)">-</a><input class="price" data-role="none" type="hidden" name="product_price" value="{$list['price']}"><input class="number" data-role="none" type="text" name="product_num" value="{$select_num}" readonly="readonly"><a class="add" data-role="none" href="javascript:void(0)">+</a>
              </span>
              <span class="btn detail-btn" type="button"><span onclick="location.href='{$detai_url}'">{$btn}</span></span>
            </p>
            {$hos}
            <div class="clearfix"></div>
          </li>
EOT;
        } //end foreach;
        //var_dump($html);exit;
      }

      $json=array(
        'product_count'=>$lists->num_rows(),
        'product_html'=>$html,
      );
      echo json_encode($json);
    }
  }

  //獲取幻燈片圖片
  private function _get_adv($var='home',$position='banner1'){
    if(!empty($var)){
      $this->load->model('advertisings_mdl');
      $filter=array('category'=>$var,'status'=>1,'position'=>$position);
      $this->data[$position]=$this->advertisings_mdl->get_advertisings($filter);
    }
  }
    //獲取菜單圖片
    private function _get_menu($var='home',$position='menu'){
        if(!empty($var)){
            $this->load->model('menuimage_mdl');
            $filter=array('category'=>$var,'status'=>1,'position'=>$position);
            $this->data[$position]=$this->menuimage_mdl->get_menuimage($filter);
        }
    }
    //獲取logo圖片
    private function _get_logo($var='home',$position='menu'){
        if(!empty($var)){
            $this->load->model('logoimg_mdl');
            $filter=array('status'=>1);
            $this->data[$position]=$this->logoimg_mdl->get_logoimg($filter);
        }
    }

  //轉換購物車的產品
  private function _get_product_array($str=''){
    $str=str_replace('{','',$str);
    $str=str_replace('}','',$str);
    $data=array();
    if(!empty($str)){
      $str_array=explode(',',$str);
      foreach ($str_array as $obj) {
        $obj_array=explode(':',$obj);
        if(!empty($obj_array) && is_array($obj_array) && count($obj_array)==2){
          $data[$obj_array[0]]=$obj_array[1];
        }
      }
    }
    return $data;
  }

  //ajax 提交訂單
  public function order(){
    $product_string=$this->input->post('product_string',true);//購物車的東西
    $cart_array=$this->_get_product_array($product_string);
    $cart_arr = $this->getCartArr();
    $notify=array('msg'=>'對不起參數錯誤,您的訂單提交失敗!','codes'=>'2');
    if(!isset($cart_arr) || empty($cart_arr['data'])){
      echo json_encode($notify);exit;
    }
    if(!empty($cart_arr) && is_array($cart_arr)){
      $cart_total_price=$this->input->post('cart_total_price');//訂單總價
      $cart_total_num=$this->input->post('cart_total_num');//訂單產品數量
      $this->load->model('orders_mdl');
      $invoice_no = date('ymd').substr(time(),-5).substr(microtime(),2,5);//隨機訂單號不順序
      $data=array(
        'invoice_no'=>$invoice_no,
        'nickname'=>'--',
        'phone'=>'--',
        'address'=>'--',
        'order_time'=>$this->input->post('order_time'),
        'order_way'=>$this->input->post('order_way'),
        'table_num'=>$this->input->post('table_num'),
        'comment'=>'--',
        'total'=>$cart_arr['total'],
        'product_num'=>$cart_arr['num'],
        'order_status_id'=>2,//待處理
        'update_time'=>time(),
        'add_time'=>time(),
      );
      $order_id=$this->orders_mdl->add_orders($data);
      if($order_id){
        $cart_product=array();
        $this->load->model('ordersproduct_mdl');
        foreach ($cart_arr['data'] as $id=>$item) {
          $filter=array(
            'id'=>$id,
            'language_id'=>$this->data['lang_id'],
            'status'=>1,
          );
          //$list=$this->products_mdl->get_products_by_unique_url($filter);
          $subtotal=$item['price']*$item['num'];
          $order_product=array(
            'order_id'=>$order_id,
            'product_id'=>$item['id'],
            'name'=>$item['title'],
            'model'=>$item['unit'],
            'color'=>$item['main_image'],
            'quantity'=>$item['num'],
            'price'=>$item['price'],
            'total'=>$subtotal,
            'specs'=>$item['spec'],
            'pname'=> isset($item['pname']) ? $item['pname'] : '',
            'pos_id'=>$item['pos_id'],
            'attrs' => isset($item['attrArr']) && count($item['attrArr']) > 0 ? serialize($item['attrArr']) : null,
          );
          $this->ordersproduct_mdl->add_ordersproduct($order_product);
          $cart_product[]=$order_product;
        }// end foreach
        
        $this->_order_integral($data);//判斷是否老客戶 和 積分計算.
        // }else{
        $success_message=$this->data['copyright'].'==訂單通知';
        $content='<p>有一位客戶落單，訂單內容如下：</p>';
        $content.='<p>訂單編號:'.$data['invoice_no']."</p>";
        $content.='<p>客戶稱呼:'.$data['nickname']."</p>";
        $content.='<p>客戶電話:'.$data['phone']."</p>";
        $content.='<p>方式:'.$data['order_way']==1?'自取':'外送'."</p>";
        if($data['order_way']==2){
          $content.='<p>送到地址:'.$data['address']."</p>";
          $content.='<p>送到時間:'.$data['order_time']."</p>";
        }
        $content.='<p>訂單總額:MOP$'.$data['total']."</p>";

        $content.='<p>點選內容:</p>';
        if(!empty($cart_product) && is_array($cart_product)){
          foreach ($cart_product as $pro) {
            $content.=$pro['name'].' X '.$pro['quantity']."<br/>";
          }
        }
    $content.='<p>桌號:'.$data['table_num']."</p>";
        $content.='<p>備註:'.$data['comment']."</p>";
        $content.='<p>落單時間:'.date('Y/m/d,H:i')."</p>";
        //$this->_send_email($success_message,$content); //發送給店主
        // }
        $order_way  = 1;//$this->input->post('order_way');
        $payment = $this->orders_mdl->get_one_payment($order_way);
        if($payment){  //第三方支付
            $option = unserialize($payment['options']);
            $config = array(
              'business' => $option['email'],
              'return_url'=>"http://".$_SERVER['SERVER_NAME'].'/home/callback?invoice_no='.$invoice_no,
              'notify_url'=>"http://".$_SERVER['SERVER_NAME'].'/home/notify',
              'driver'=>$order_way,
              'currency_code' => $option['currency_code']
          );
          // echo dirname(dirname(__FILE__));
          $this->load->library('payment',$config);
          $pay = $this->payment->getDriver();
          $data['title'] = $this->data['web_title'];
          $data['entitle'] = isset($this->data['web_entitle']) ? $this->data['web_entitle'] : null;
          $pay->setFormData($data);
          $html = $pay->buildRequestForm();
          $notify = array('codes'=>3,'msg'=>$html);
          $this->nsession->set_session('carts',null);
          $this->nsession->set_session('cart_attrs',null);
          //echo json_encode(array('codes'=>3,'msg'=>$html));
          //exit;
        } else{
          $notify['msg']='你的訂單已成功提交，訂單編號為：'.$invoice_no.'，我們會盡快聯絡你確認訂單，謝謝。<script src="'.base_url('api/account/posprint?order_id='.$order_id).'"></script><script src="'.base_url('api/orders/yprint?order_id='.$order_id).'"></script>';
          $notify['codes']=1;
          //判斷是否為澳門電話
          if(!empty($data['phone']) && strlen($data['phone'])==8){
            if($this->data['sms_status']==1){//是否開啟發送短信給客戶
              $this->_send_sms($data);//發送短信給客戶
            }
          }
          if($this->data['sms_shop_status']==1){//是否開啟發送短信給店主
             $this->_send_shop_sms($data,$cart_product);//發送短信給店主(打印詳細)
          }
          $palyerid = $this->admins_mdl->get_member_palyers();
          $this->load->library('message');
          if(count($palyerid) > 0){
              $this->message->sendMessage($palyerid, '您好！您有新的訂單消息，請注意查收！' . date('Y-m-d H:i:s'));
          }
          $this->nsession->set_session('carts',null);
          $this->nsession->set_session('cart_attrs',null);
          /*下單成功的*/
        }
        
      }else{
        $notify['msg']='對不起,訂單載入失敗!';
        $notify['codes']=2;
      }
    }
    echo json_encode($notify);
  }

  //推送email通知
  private function _send_email($success_message='',$content='',$cc=''){
    $protocol= $this->data['default_email_type']; //email發送方法
    $email_to= $this->data['email_to']; //email接收者
    $email_host= $this->data['email_host']; //Email發出者
    $email_form= $this->data['email_form']; //發出者名字
    $smtp_host= $this->data['smtp_host']; //smtp地址smtp_password
    $smtp_password= $this->data['smtp_password']; //賬戶密碼
    $smtp_port= $this->data['smtp_port']; //服務器端口

    header('Content-Type: text/html; charset=UTF-8');
    $config['protocol']=($protocol==1)?'mail':'smtp';
    if($protocol==2){
      $config['smtp_host']    = $smtp_host;
      $config['smtp_user']    = $email_host;
      $config['smtp_pass']    = $smtp_password;
      $config['smtp_port']    = $smtp_port;
      $config['smtp_timeout'] = '5';
    }
    $config['charset']      = 'utf-8';
    $config['mailtype']     = 'html';
    $config['newline'] = "\r\n";
    $this->load->library('email',$config);
    $this->email->from($email_host,$email_form);
    $this->email->to($email_to);
    if(!empty($cc)){
      $this->email->cc($cc);
    }
    $this->email->subject($success_message);
    $this->email->message($content);
    return $this->email->send();
  }


  //推送sms通知給客戶
  //xxx:您好,您的訂單已經成功提交,我們將很快與您聯絡. 訂單編號:xxx,總額:xxx, 地址是:xxxx,[家和]
  private function _send_sms($data=array()){
    if(!empty($data) && is_array($data)){

      if(($this->data['sms_count']-1)>0){
        if ($data['order_status_id'] == 1) {
                $message_txt = '【' . $this->data['copyright'] . '】您好,您的訂單已經提交,我們將很快與您聯絡.';
                $message_txt .= '訂單編號:' . $data['invoice_no'] . ',總額:$' . $data['total'] . " HKD ";
                $message_txt .= '催單電話:' . $this->data['telephone'];
                if ($this->data['integral_status'] == 1 && isset($this->data['phone_integral']) && $this->data['phone_integral'] > 0) { //啟用積分
                    $message_txt .= ',累計積分:' . $this->data['phone_integral'];
                }
                //$send_result=helper_send_macau_sms($data['phone'],$message_txt);//發送短信
                $send_result = send_sms($message_txt, $data['phone']);
                $send_data = array(
                    'phone_number' => $data['phone'],
                    'message_txt' => $message_txt,
                    'send_result' => $send_result,
                    'phone_area' => '客戶',
                    'send_date' => time(),
                    'add_time' => time(),
                    'update_time' => time(),
                );
            } else if ($data['order_status_id'] == 4) {
                $message_txt = '【' . $this->data['copyright'] . '】您好,您的訂單已被取消,歡迎您再次光臨.';
                $message_txt .= '訂單編號:' . $data['invoice_no'] . ',總額:$' . $data['total'] . " HKD ";
                if ($this->data['integral_status'] == 1 && isset($this->data['phone_integral']) && $this->data['phone_integral'] > 0) { //啟用積分
                    $message_txt .= ',累計積分:' . $this->data['phone_integral'];
                }
                //$send_result=helper_send_macau_sms($data['phone'],$message_txt);//發送短信
                $send_result = send_sms($message_txt, $data['phone']);
                $send_data = array(
                    'phone_number' => $data['phone'],
                    'message_txt' => $message_txt,
                    'send_result' => $send_result,
                    'phone_area' => '客戶',
                    'send_date' => time(),
                    'add_time' => time(),
                    'update_time' => time(),
                );
            }
        //$this->_sms_count_modify($send_result);
      }else{
        $success_message=$this->data['copyright'].'==短信餘額不足';
        $content='<p>您好,您的短信餘額不足,請及時充值：</p>';
        $content.='<p>剩餘短信條數:<span style="color:red">0</span></p>';
        $content.='<p>詳情聯絡Clickr 力嘉電話:+(853) 2823 1274</p>';
        $content.='<p>或瀏覽網站:<a href="http://clickrweb.com">http://clickrweb.com</a></p>';
        $content.='<p>發送時間:'.date('Y/m/d,H:i')."</p>";
        $this->_send_email($success_message,$content,'info@clickrweb.com'); //發送給店主
      }
    }
  }

  //發送給店主
  //發送給打印機
  private function _send_shop_sms($data=array(),$cart_product=array()){
    if(!empty($data) && is_array($data) && !empty($cart_product)){
      if(($this->data['sms_count']-1)>0  && !empty($this->data['sms_shop_phone'])){
        $item_string='';
        foreach ($cart_product as $item) {
          $item_string.=<<<EOT
{$item['name']}%%            {$item['price']}         {$item['quantity']}%%
EOT;
        }
        $order_way=$data['order_way']==1?'自取':'外送';
        $order_address=$data['order_way']==2?'外送地址：'.$data['address']:'';
        $comment=!empty($data['comment'])?'備註：'.$data['comment']:'';
        $member_tag=$this->data['phone_order_count']>1?'  *[熟客]':'';
        $message_txt='%10 '.$this->data['copyright'].'%%%00';
        $message_txt.='%%菜品        單價         數量%%';
        $message_txt.='-----------------------------';
        $message_txt.=$item_string;
        $message_txt.='-----------------------------';
        $message_txt.='%%%10【'.$order_way.'】        總計：'.$data['total'].'%%%00';
        $message_txt.='-----------------------------%%';
        $message_txt.='聯絡電話：'.$data['phone'].$member_tag.'%%';
        $message_txt.='顧客稱呼：'.$data['nickname'].'%%';
        $message_txt.=!empty($order_address)?$order_address.'%%':'';
        $message_txt.=!empty($comment)?$comment.'%%':'';
        $message_txt.='訂購時間：'.date('Y-m-d H:i:s').'%%';
        $message_txt.='訂單編號：'.$data['invoice_no'];

        //$send_result=helper_send_macau_sms($this->data['sms_shop_phone'],$message_txt);//發送短信
        $send_result = send_sms($message_txt,$this->data['sms_shop_phone']);
        $send_data=array(
          'phone_number'=>$this->data['sms_shop_phone'],
          'message_txt'=>$message_txt,
          'send_result'=>$send_result,
          'phone_area'=>'店主',
          'send_date'=>time(),
          'add_time'=>time(),
          'update_time'=>time(),
        );
        $this->load->model('sms_mdl');
        $this->sms_mdl->add_sms($send_data);
        $this->_sms_count_modify($send_result);
      }else{
        $success_message=$this->data['copyright'].'==短信餘額不足';
        $content='<p>您好,您的短信餘額不足,請及時充值：</p>';
        $content.='<p>剩餘短信條數:<span style="color:red">0</span></p>';
        $content.='<p>詳情聯絡Clickr 力嘉電話:+(853) 2823 1274</p>';
        $content.='<p>或瀏覽網站:<a href="http://clickrweb.com">http://clickrweb.com</a></p>';
        $content.='<p>發送時間:'.date('Y/m/d,H:i')."</p>";
        $this->_send_email($success_message,$content,'info@clickrweb.com'); //發送給店主
      }
    }
  }

  //查詢是否老客戶
  private function _order_integral($data=array()){
    if(!empty($data) && is_array($data)){
      $this->load->model('orders_mdl');
      $this->data['phone_order_count']=$this->orders_mdl->totle_orders(array('phone'=>$data['phone'],'order_status_id'=>2));
      if($this->data['integral_status']==1){ //啟用積分
        $this->load->model('integral_mdl');
        $row=$this->integral_mdl->get_one_integral(array('phone'=>$data['phone']));
        if(!empty($row) && is_array($row)){
          $this->data['phone_integral']=$row['integral'];
        }
      }
    }// end if data
  }

  //扣除短信數
  //如果短信數不夠 send email提示
  private function _sms_count_modify($send_result){
    $sms_count=$this->data['sms_count']-1;
    if(!empty($send_result) && $send_result=='發送成功'){
      $this->load->model('settings_mdl');
      $setting=array(
        'group'=>'other',
        'key'=>'sms_count',
        'value'=>$sms_count
      );
      $this->settings_mdl->edit_settings_by_keyGroup($setting);
    }
    //如果短信數不夠 send email提示
    if($sms_count<=$this->data['sms_remind']){
      $success_message=$this->data['copyright'].'==短信餘額不足';
      $content='<p>您好,您的短信餘額不足,請及時充值：</p>';
      $content.='<p>剩餘短信條數:<span style="color:red">'.$sms_count."</span></p>";
      $content.='<p>詳情聯絡Clickr 力嘉電話:+(853) 2823 1274</p>';
      $content.='<p>或瀏覽網站:<a href="http://clickrweb.com">http://clickrweb.com</a></p>';
      $content.='<p>發送時間:'.date('Y/m/d,H:i')."</p>";
      $this->_send_email($success_message,$content,'info@clickrweb.com'); //發送給店主
    }
  }

  //load page info
  public function _page_info($unique_url=''){
    $filter=array(
      'status'=>1,
      'unique_url'=>$unique_url,
      'language_id'=>$this->data['lang_id'],
    );
    $this->load->model('pages_mdl');
    if(!empty($unique_url)){
      $query=$this->pages_mdl->get_pages_by_unique_url($filter_data);
      if(!empty($query) && is_array($query)){
        $this->data[$unique_url]=$query['content'];
      }
    }else{
      $this->data['page_list']=$this->pages_mdl->get_pages($filter);
    }
  }

  //搜索訂單信息
  public function search(){
    header('Content-Type: application/json; charset=utf-8');
    $invoice_no=$this->input->post('order_number');
    $json=array();
    if(!empty($invoice_no) && is_numeric($invoice_no)){
      $this->load->model('orders_mdl');
      //defalut_orderStatus
      $order=$this->orders_mdl->get_one_order(array('invoice_no'=>$invoice_no));
      if(!empty($order) && is_array($order) && isset($order['id'])){
        $order_way=$order['order_way']==1?'自取':'送到上門';
        $order_address=$order['order_way']==2?'<tr><td><b>送到地址</b>：'.$order['address'].'</td><td><b>送到時間</b>：'.$order['order_time'].'</td></tr>':'';
        $order_total='$'.$order['total'];
    $order_tablenum=!empty($order['table_num'])?'<tr><td coslapn="2"><b>桌號</b>：'.$order['table_num'].'</td></tr>':'';
        $order_comment=!empty($order['comment'])?'<tr><td coslapn="2"><b>備註</b>：'.nl2br($order['comment']).'</td></tr>':'';
        $json['order_detail']=<<<EOT
        <table>
      <tr>
        <td coslapn="2"><b>訂單編號</b>：{$order['invoice_no']}</td>
      </tr>
          
          <tr>
            <td><b>訂單總額</b>：{$order_total}</td>
            <td><b>選購數量</b>：{$order['product_num']}</td> 
          </tr>
      <tr>
            
          
        </table>
EOT;
        $json['order_product']='';
        $this->load->model('ordersproduct_mdl');
        $products=$this->ordersproduct_mdl->get_ordersproduct(array('order_id'=>$order['id']));
        if(!empty($products) && $products->num_rows()>0){
          foreach ($products->result_array() as $list) {
            $thumb_img=!empty($list['color']) && file_exists($list['color'])?base_url(Imagelib::resize_thumb($list['color'],100,57,FALSE)):base_url('themes/front/img/no-image.png');
            $large_image=!empty($list['color']) && file_exists($list['color'])?base_url(Imagelib::resize_thumb($list['color'],800,450,FALSE)):base_url('themes/front/img/no-image-large.png');
            $price='$'.$list['price'];
            $attrStr = '';
            if(!empty($list['attrs'])){
                $attrArr = unserialize($list['attrs']);
                if($attrArr){
                    foreach($attrArr as $attr){
                        $attrStr .= "<span class='atrr_str'>".$attr['name']."".$attr['num']."份</span> ";
                    }
                }
            }
            $json['order_product'].=<<<EOT
            <li class="product">
              <div class="cover">
                <figure class="cover_son" itemprop="associatedMedia" itemscope>
                <a href="{$large_image}" itemprop="contentUrl" data-size="800x450">
                  <img src="{$thumb_img}" itemprop="thumbnail" alt="Image description" width="100" height="57" /><i></i>
                </a>
                </figure>
              </div>
              <p class="title">{$list['name']}</p>
              <p class="title">{$attrStr}</p>
              <p class="price">{$price}/{$list['model']}</p>
              <p>
                選購：{$list['quantity']}
              </p>
              <div class="clearfix"></div>
            </li>
EOT;
          }

        }// end if products

      } //end if order

    } //end if order_number
    echo json_encode($json);
  }
  public function notify(){
       $invoice_no = $this->input->post('invoice');
       $receiver_email = $this->input->post('receiver_email');
       $mc_gross = $this->input->post('mc_gross');
       $order = $this->orders_mdl->get_one_order(array('invoice_no'=>$invoice_no));
       if(!$order){
          exit('NOT Order...');
       }
        $payment = $this->orders_mdl->get_one_payment('paypal');
        if(empty($payment)){
           exit('NOT Payment');
        }
        $option = unserialize($payment['options']);
        if($option['email'] != $receiver_email){
             exit('Account verification error');
        }
        if($order['total'] != $mc_gross){
            exit('The amount is wrong');
        }
        $data['pay_status'] = 1;
        $data['pay_time'] = date('Y-m-d H:i:s',time());
        if($this->orders_mdl->edit_orders($data,$order['id'])){
          //判斷是否為澳門電話
          if(!empty($order['phone']) && strlen($order['phone'])==8){
            if($this->data['sms_status']==1){//是否開啟發送短信給客戶
              $this->_send_sms($order);//發送短信給客戶
            }
          }
          if($this->data['sms_shop_status']==1){//是否開啟發送短信給店主
            $this->_send_shop_sms($order,$cart_product);//發送短信給店主(打印詳細)
          }
           exit('success');
        }
        exit('error');
  }
  public function callback(){
       $invoice_no = $this->input->get('invoice_no');
       $order = $this->orders_mdl->get_one_order(array('invoice_no'=>$invoice_no));
       if($order && $order['pay_status'] == 1){
          $msg = array('status'=>1,'title'=>'成功提示','content'=>'你的訂單已成功提交，訂單編號為：'.$invoice_no.'，我們會盡快聯絡你確認訂單，謝謝。');
       }else{
          $msg = array('status'=>0,'title'=>'失敗提示','content'=>'你的訂單提交失敗，請重新下單，謝謝。');
       }
       $data['msg'] =  $msg;
       $this->load->view('prompt_view',$data);
  }
  public function popupSpecItem(){

     $product_id = (int)$this->input->get_post('product_id');
     $lang_id = $this->data['default_language'];
     if($product_id>0){
        // $itemArray = array();
        // $itemPrice = $this->products_mdl->getItemPrice($product_id,$itemArray);
        // if(empty($itemPrice)) return false;
        // $FisrtItemPrice = array_keys($itemPrice);
        // $defaultPrice = $itemPrice[$FisrtItemPrice[0]]['price'];
        // $checkboxArr = $this->specs_mdl->get_items_checkbox_array($product_id,$this->data['getlang']);
        // if($checkboxArr){
        //     $itemArray = array_merge(array_values($itemArray),$checkboxArr);
        // }
        //$items = $this->products_mdl->getProductItemPrice($itemArray);
        $row = redCache("spec_items_".$product_id);
        //var_dump($specs);exit;

        if($row){
            $defaultItem = $row['defaultItem'];
            $carts = $this->nsession->userdata('carts');
            $catsArr = isset($carts[$product_id]) ? $carts[$product_id] : array();
            $num = isset($carts[$product_id][$defaultItem]) && $carts[$product_id][$defaultItem] > 0 ? $carts[$product_id][$defaultItem] : 1;
            $defaultItem = $row['defaultItem'];
            $defaultItemArr = explode("_", $defaultItem);
            //$row  = $this->products_mdl->get_descriptions($product_id,$lang_id)->row_array();
            $html = '<div class="popupMask popup"></div>';
            $html .= '<div class="popuplayout popup">';
            $html .= '<div class="popup-title">'.$row['name'].'</div>';
            $html .='<div class="popup-content">';
            $html .= '<dl>';
            //$spec = $this->specs_mdl->getSpecField(null);
            $itemPriceOne = $this->products_mdl->getProductItemPriceOne(array('spec_key'=>$defaultItem,'product_id'=>$product_id));
            $defaultPrice = (float)$itemPriceOne['price'];
            $specList = $row['specList'];
            uasort($specList, "sort_spec"); //排序，以sort字段
            foreach($specList as $spec_id => $item){
                $trans = '';
                if($item['is_trans'] == 1){
                    $trans = "(任選)";
                }
                if ($this->data['getlang'] == 'zh-tw'){
                        $html .= '<dt>' . (isset($item['name']) ? $item['name'] : '') . ' ：'.$trans.'</dt>';
                }else{
                        $html .= '<dt>' . (isset($item['name_en']) ? $item['name_en'] : '') . ' ：'.$trans.'</dt>';
                }
                $html .='<dd>';
                foreach($item['items'] as $item_id=>$v){
                   if($item['is_trans'] != 1){
                      $on = in_array($item_id, $defaultItemArr) ? 'on' : '';
                   }else{
                      $on = '';
                   }

                   if ($this->data['getlang'] == 'zh-tw') {
                        $html .= $item['is_trans'] == 1 ? "<label class='attr_label'><span data-price='".$v['price']."' class='attr-item $on' data-spec='".$spec_id."' data-product='" . $product_id . "' data-aid='" . $item_id . "'>" . $v['name'] . "</span></label>" : "<span data-price='".$v['price']."' class='spec-item $on' data-product='" . $product_id . "' data-aid='" . $item_id . "'>" . $v['name'] . "</span>";
                    }else{
                        $html .= $item['is_trans'] == 1 ? "<label class='attr_label'><span data-price='".$v['price']."' class='attr-item $on' data-spec='".$spec_id."' data-product='" . $product_id . "' data-aid='" . $item_id . "'>" . $v['name'] . "</span></label>" : "<span data-price='".$v['price']."' class='spec-item $on' data-product='" . $product_id . "' data-aid='" . $item_id . "'>" . $v['name_en'] . "</span>";
                    }
                }
                 $html .='</dd>';
             }

             // $checkbox = $this->specs_mdl->get_items_checkbox($product_id,$this->data['getlang']);
             // if($checkbox){
             //    foreach($checkbox as $mspec_id=>$val){
             //        $on = '';
             //        $html .= '<dt>' . $val['name'] . ' ： (任選)</dt>';
             //        $html .='<dd>';
             //        foreach($val['items'] as $i=>$v){
             //            $html .= "<label class='attr_label'><span class='attr-item $on' data-spec='".$mspec_id."' data-product='" . $product_id . "' data-aid='" . $v['id'] . "'>" . $v['name'] . "</span></label>";
             //        }
             //        $html .='</dd>';
             //    }
             // }
             $html .='</dl>';
             $html .='</form></div><div class="popupFooter">';
             $html .="<span class='_price' id='_mprice' data-price='".format_free($defaultPrice)."'>$".format_free($defaultPrice)."</span>";

             if(isset($carts[$product_id][$defaultItem]) && $carts[$product_id][$defaultItem] >0){
                $btn_str = $this->data['lang']['home_lable_4'];
                $html .= '<div class="addcartbtn order-item"><p class="select"><a data-product="'.$product_id.'" class="minus popup" data-role="none" href="javascript:void(0)">-</a><input class="number" data-role="none" type="text" name="product_num" value="'.$carts[$product_id][$defaultItem].'" readonly="readonly"><a class="add popup" data-role="none" href="javascript:void(0)" data-product="'.$product_id.'">+</a></p></div>';
             }else{
                 $text = $this->data['lang']['home_lable_3'];
                $html .='<div class="addcartbtn order-item"><button class="push-cart" type="button" data-product="'.$product_id.'">'.$text.'</button></div>';
                $btn_str = $this->data['lang']['home_lable_5'];
             }
             $html .="<div class='closebtns'><button class='_confirm_btn _close' id='_close' type='button'>".$btn_str."</button></div>";
             $html .='<div class="clearfix"></div></div></div>';
             exit(json_encode(array('status'=>1,'html'=>$html,'jsonData'=>'','attrItems'=>isset($this->cart_attrs[$product_id]) ? $this->cart_attrs[$product_id] : '','selectdSpecKey'=>$defaultItem)));
            //exit(json_encode(array('status'=>1,'html'=>$html,'jsonData'=>$itemPrice,'attrItems'=>$this->cart_attrs[$product_id],'selectdSpecKey'=>$FisrtItemPrice[0])));
        }
     }
     exit(json_encode(array('status'=>0,'html'=>'','jsonData'=>'','attrItems'=>'')));
  }
  /*加入购物车*/
    public function addCart(){
        $product_id = (int)$this->input->get_post('product_id');
        if($product_id <= 0 ){
            return false;
        }
        $num = (int)$this->input->get_post('product_num');
        $spec_key = $this->input->get_post('spec_key');
        $attrs = $this->input->get_post('attrs');
        $result = $this->carts_mdl->addProductToCard($product_id,$num,$spec_key,$attrs);
        echo json_encode(array("num"=>$this->carts_mdl->getCartTotal(),'nownum'=>$num,'cart'=>$this->carts_mdl->getCartProduct()));exit;
    }
  /*获取购物车商品数量*/
   public function getCartTotal($carts){
        if(empty($carts)) return 0;
        $num = 0;
        foreach($carts as $cat){
            if(is_array($cat)){
                foreach($cat as $n){
                    $num +=(int)$n;
                }
            }else if(is_numeric($cat)){
                $num +=(int)$cat;
            }
        }
        return $num;
   }
   public function getCartList(){
    
        echo json_encode($this->getCartArr());
   }
   public function getCartArr(){
       $attrs = array();
       $carts = $this->carts_mdl->getCartProduct($attrs);
       print_r($carts);exit;
       $base = array();
       $num = 0;
       $total = 0;
       if(!empty($carts)){
           $product_ids = array_keys($carts);
           $query = $this->products_mdl->get_products(array('product_ids'=>$product_ids));
           $result = $query->result_array();
           if($result){
               foreach($result as $i=>$item){
                   $title = $item['title'];
                   $item['pname'] = $title;
                   if(isset($carts[$item['id']]) && is_array($carts[$item['id']])){
                       foreach($carts[$item['id']] as $spec_key=>$nums){
                           $itemp = $this->products_mdl->getItemSku($item['id'],$spec_key);
                           $item['title'] =  $title." ".(isset($itemp['spec_name']) ? $itemp['spec_name']:'');
                           $item['num'] = (int)$nums;
                           $item['price'] =  isset($itemp['price']) ? $itemp['price']:0.00;
                           $item['spec'] =  $spec_key;
                           $num += (int)$nums;
                           $item['attrStr'] = null;
                           $item['attrArr'] = null;
                           $arrtPrice = 0;
                           if(isset($attrs[$item['id']."_".$spec_key]) && !empty($attrs[$item['id']."_".$spec_key])){
                               $attrArr = $attrs[$item['id']."_".$spec_key];
                               $attrItems = $this->specs_mdl->_get_itemsBYIds(array_keys($attrArr),'');
                               if($attrItems){
                                   foreach($attrItems as $attr){
                                       $attr['num'] = $attrArr[$attr['id']];
                                       $item['attrStr'] .= "<span class='atrr_str'><em class='attr-item on' data-aid='".$attr['id']."'><input type='hidden' class='attr_total' value='".$attrArr[$attr['id']]."' name='attrs[".$attr['id']."]' /></em>".$attr['name']." ".$attrArr[$attr['id']]." 份</span>";
                                       $item['attrArr'][] =$attr;
                                       $item['price'] += $attrArr[$attr['id']] > 0 ? $attrArr[$attr['id']]*$attr['price'] : 0;
                                   }
                               }
                           }
                           $total += $item['price']*$item['num'];
                           $base[] = $item;
                       }
                   }else{
                       $item['attrStr'] = null;
                       $item['attrArr'] = null;
                       $item['num'] = (int)$carts[$item['id']];
                       $num += (int)$item['num'];
                       $total += $item['price']*$item['num'];
                       $item['spec'] =  0;
                       $base[] = $item;
                   }
               }
           }
       }
       return array('num'=>$num,'total'=>sprintf("%.2f",$total),'data'=>$base);
   }
   public function getItemSku(){
       $product_id = $this->input->get_post('product_id');
       $row = redCache("spec_items_".$product_id);
       $itemArr = $this->input->get_post('itemArr');
       sort($itemArr);
       $key = implode("_", $itemArr);
       $unitPrice = $this->specs_mdl->getProductItemUnitPrice($key);
       $price = $row['price']+$unitPrice;
       $cart = $this->carts_mdl->getCartItem($product_id,$key);
       $base = array("price"=>format_free($price),'nownum'=>0,'key'=>$key);
       $base['num'] = 0;
       $base['attrs'] = array();
       if($cart){
           $base['num'] = $cart['num'];
           $base['attrs'] = empty($cart['attrs']) ? array() : unserialize($cart['attrs']);
       }
       echo json_encode($base);exit;
   }
    
}
